package com.mairuide.datalog;

import com.mairuide._frame.base.BaseRepository;
import com.mairuide._frame.base.BaseServiceProxy;
import com.mairuide._frame.utils.StringUtils;
import com.mairuide._frame.utils.Testtrans;
import com.mairuide.entity.PageResult;
import org.hibernate.SQLQuery;
import org.hibernate.transform.Transformers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class DataOperationImportLogService extends BaseServiceProxy<DataOperationImportLog> {
	
	@Resource
	private DataOperationImportlLogRepository dataOperationImportlLogRepository;
	@Autowired
	private JdbcTemplate jdbcTemplate;
	@PersistenceContext
	private EntityManager entityManager;
	
	@Override
	protected BaseRepository<DataOperationImportLog> getBaseRepository() {
		return dataOperationImportlLogRepository;
	}
	
	/**
	 * 查询文件hash值是否存在
	 * @param dealFlowUuid	
	 * @param isDelete
	 * @param tableFlat
	 * @return
	 */
	public List<DataOperationImportLog> findByDealFlowUuidAndIsDeleteAndTableFlat(String dealFlowUuid,String caseId,Integer tableFlag) {
		return dataOperationImportlLogRepository.findByDealFlowUuidAndCaseManagerIdAndIsDeleteAndTableFlatAndImportResult(dealFlowUuid,caseId,0,tableFlag,"成功");
		
	}
	/**
	 * 根据日志父表id查询导入日志详情信息
	 * @param parentLogId
	 * @return
	 */
	public List<DataOperationImportLog> findByParentLogIdOrderByImportDetailId(Integer parentLogId){
		return dataOperationImportlLogRepository.findByParentLogIdOrderByImportDetailId(parentLogId);
	}
	
	/**
	 * 根据案件编号查询导入日志详情信息
	 * @param caseManagerId
	 * @return
	 */
	public List<DataOperationImportLog> findByDealFlowUuid(String caseManagerId){
		return dataOperationImportlLogRepository.findByCaseManagerIdAndIsDeleteAndTableFlat(caseManagerId,0,1);
	}
	
	public void deleteByCaseManagerId(String caseManagerId) {
		dataOperationImportlLogRepository.deleteByCaseManagerId(caseManagerId);
	}
	/**
	 * 根据案件编号查询该案件下导入文件信息
	 * @param opip
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public PageResult<DataOperationImportLog> findDataOperationImportLogByPage(DataOperationImportParams opip) {
		StringBuffer selectSql = new StringBuffer();
		selectSql.append("select t.id as importDetailId, t.file_name as fileName,t.success_number as successNumber, ");
		selectSql.append("t.deal_flow_uuid as dealFlowUuid, t.table_flat as tableFlag,t.CASEMANAGE_ID as caseManagerId, ");
		selectSql.append("t.file_size as fileSize, t.create_time as createTime,t.user_id as userId ");
		StringBuffer fromWhereSql = new StringBuffer();
		fromWhereSql.append(" from TB_DATA_OPERATION_IMPORT_LOG t ");
		fromWhereSql.append("where t.IS_DELETE=0 ");
		if(StringUtils.isNotEmpty(opip.getCaseUuid())) {
			fromWhereSql.append("and t.CASEMANAGE_ID= '"+opip.getCaseUuid()+"' ");
		}
		if(StringUtils.isNotEmpty(opip.getTableFlag())) {
			fromWhereSql.append("and t.TABLE_FLAT= '"+opip.getTableFlag()+"' ");
		}
		if(StringUtils.isNotEmpty(opip.getFileName())) {
			fromWhereSql.append("and t.FILE_NAME like '%"+opip.getFileName()+"%' ");
		}
		if(StringUtils.isNotEmpty(opip.getSort())) {
			fromWhereSql.append("order by t.CREATE_TIME "+opip.getOrder());
		}else {
			fromWhereSql.append("order by t.CREATE_TIME desc");
		}
		long count = jdbcTemplate.queryForObject("select count(1) from ("+selectSql.toString()+fromWhereSql.toString()+") a ",long.class);
		Query query = entityManager.createNativeQuery(selectSql.toString()+fromWhereSql.toString());
		//将查询结果集转为Map
		query.unwrap(SQLQuery.class).setResultTransformer(new Testtrans(DataOperationImportLog.class));		//设置分页
		query.setFirstResult((opip.getPage() - 1) * opip.getRows());
		query.setMaxResults(opip.getRows());
		//获取查询结果集
		List<DataOperationImportLog> list = query.getResultList();
		PageResult pageResult = new PageResult(count,list);
		return pageResult;
	}
	
	/**
	 * 根据案件编号查询导入日志详情信息加分页
	 * @param caseManagerId
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public PageResult findByDealFlowUuidPage(String caseManagerId, Integer pageNumber, Integer pageSize,String ids){
		String sql = "select ID as IMPORTDETAILID,PARENT_LOG_ID,FILE_NAME,SUCCESS_NUMBER,DEAL_FLOW_UUID,TABLE_FLAT,ERROR_NUMBER,CASEMANAGE_ID,IMPORT_RESULT,IMPORT_DESC,FILE_SIZE from TB_DATA_OPERATION_IMPORT_LOG where IS_DELETE = 0 AND CASEMANAGE_ID='"+caseManagerId+"'";
		if (!org.apache.commons.lang3.StringUtils.isBlank(ids)){
			sql+=" and ID in (" + ids + ")";
		}
		List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql);
		Query query = this.entityManager.createNativeQuery(sql);
		// 将查询结果集转为Map
		query.unwrap(SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
		// 设置分页
		query.setFirstResult((pageNumber) * pageSize);
		query.setMaxResults(pageSize);
		// 获取查询结果集
		List<Map<String, Object>> list = query.getResultList();
		PageResult pageResult = new PageResult(Long.valueOf(maps.size()), list);
		return pageResult;
	}
}
